package com.search.service.imp;

import java.io.IOException;

import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.NumericDocValues;
import org.apache.lucene.index.SortedDocValues;
import org.apache.lucene.queries.CustomScoreProvider;

public class RecencyBoostCustomScoreProvider extends CustomScoreProvider {
	// Ȩ�ر���
	private double multiplier;
	// ��1970-01-01�����������
	private int day;
	// ����������
	private int maxDaysAgo;
	// �����������
	@SuppressWarnings("unused")
	private String dayField;
	// �򻺴�ֵ
	private NumericDocValues publishDay;

	@SuppressWarnings("unused")
	private SortedDocValues titleValues;

	public RecencyBoostCustomScoreProvider(LeafReaderContext context, double multiplier, int day, int maxDaysAgo,
			String dayField) {
		super(context);
		this.multiplier = multiplier;
		this.day = day;
		this.maxDaysAgo = maxDaysAgo;
		this.dayField = dayField;
		try {
			publishDay = context.reader().getNumericDocValues(dayField);
			titleValues = context.reader().getSortedDocValues("docTile");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * subQueryScore:ָ������ͨQuery��ѯ������ valSrcScore��ָ����FunctionQuery��ѯ������
	 */
	@Override
	public float customScore(int docId, float subQueryScore, float valSrcScore) throws IOException {
		// String title = "";
		// try {
		// title = titleValues.get(docId).toString();
		// } catch (Exception e) {
		// System.out.println(docId);
		// System.out.println(titleValues.get(docId));
		// System.out.println(titleValues.get(docId).utf8ToString());
		// e.printStackTrace();
		//
		// }
		int daysAgo = (int) (day - publishDay.get(docId));
		// System.out.println(title + ":" + daysAgo + ":" + maxDaysAgo);
		// �����2��֮��
		if (daysAgo < maxDaysAgo) {
			float boost = (float) (multiplier * (maxDaysAgo - daysAgo) / maxDaysAgo);
			// System.out.println("ԭ�÷�Ϊ"+subQueryScore+"���ӵ�Ȩ��Ϊ"+boost);
			return (float) (subQueryScore * (1.0 + boost));
		}
		return subQueryScore;
	}
}
